package com.bsoft.gol.hcs.his.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import ctd.net.rpc.Client;
import ctd.util.xml.jaxb.JAXBUtils;
import com.bsoft.gol.hcs.enumcase.InspectionEmum;
import hcn.base.operate.qo.QueryOperativeListQo;
import hcn.base.operate.vo.OperativeListVo;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import com.bsoft.gol.hcs.his.service.IIndexHisService;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.bsoft.gol.hcs.specialist.bean.request.QueryExamineResultIndexRequest;
import com.bsoft.gol.hcs.specialist.bean.request.QueryIndexTypeReq;
import com.bsoft.gol.hcs.specialist.bean.request.QueryQueryOperativeListNewReq;
import com.bsoft.gol.hcs.specialist.bean.response.*;
import com.bsoft.gol.hcs.utils.*;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.bsoft.gol.hcs.utils.WhisClientUtil.*;


/**
 * @Description:检查检验his服务
 * @Author: zhaorb
 * @Date: 2020/6/4 15:08
 **/
@Service
public class IndexHisService implements IIndexHisService {
    private final static Logger log = LoggerFactory.getLogger(IndexHisService.class);

    //关联类型：1-疾病、2-并发症 3-手术 4-治疗
    private static final String TREATMENT_TYPE = "4";
    private static final String OPERATE_TYPE = "3";
    private static final String COMPLICE_TYPE = "2";
    private static final String DISEASE_TYPE = "1";

    public static final String ORIGINORG = "1";

    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;

    @Override
    public BaseResponse<List<ExamineResultIndexResp>> queryExamineResultIndex(QueryExamineResultIndexRequest request) {
        String jsonContext = JSONDateUtil.readFile("ExamineResultIndexResp");
        List<ExamineResultIndexResp> list = JSONArray.parseArray(jsonContext, ExamineResultIndexResp.class);
        BaseResponse<List<ExamineResultIndexResp>> baseResponse = new BaseResponse();
        baseResponse.setData(list);
        return baseResponse;
    }

    /**
     * @Description: 获取关联手术
     * @Author: liwenlong
     * @Date: 2020/7/20 14:17
     **/
//    @Override
//    public BaseResponse<List<OperativeListResp>> queryOperativeList1(QueryOperativeListRequest request) {
//        log.info("=入参=>>>" + request.toString() + "=====");
//        String strfileName="queryOperativeList";
//
//        //if(OPERATE_TYPE.equals(request.getType())) strfileName="queryDiseaseList";
//       // else if(COMPLICE_TYPE.equals(request.getType())) strfileName="queryCompliceList";
//        BaseResponse<List<OperativeListResp>> baseResponse = new BaseResponse();
//        if(OPERATE_TYPE.equals(request.getType())) {
//            String jsonContext = JSONDateUtil.readFile("" + strfileName);
//            List<OperativeListResp> operativeListRespList = JSONArray.parseArray(jsonContext, OperativeListResp.class);
//
//            baseResponse.setData(operativeListRespList);
//
//        }else{
//            baseResponse.setData(baseWmDiseasesDAO.queryDiagnosticListByPinYin(request));
//        }
//
//        return baseResponse;
//    }
    @Override
    public BaseResponse<List<OperativeListResp>> queryOperativeList(QueryOperativeListQo request) {
        log.info("queryOperativeList-入参=>>>" + request.toString() + "=====");
        String serviceName = InspectionEmum.getValue("QueryOperationList");
        String service = "ODS_" + InspectionEmum.QueryOperationList.getCode();
        String msgType = serviceName;
        String msgHeaderXml = getMsgHeaderXml(ORIGINORG, "PHIS", msgType);
        //       String serviceCode = "<service>"+InspectionEmum.QueryOperationList.getCode()+"</service>";
        BaseResponse baseResponse = new BaseResponse();
        QueryQueryOperativeListNewReq req1 = new QueryQueryOperativeListNewReq();
        req1.setInputCode(request.getPyCode());
        req1.setVisitOrganizationCode(request.getOrganizationId());
        if (CommonUtils.isNotNull(request.getPageSize())) {
            req1.setPageSize(request.getPageSize());
            req1.setPageNo(request.getPageNo());
        }
        //转化为xml
        String xml = JAXBUtils.object2Xml(QueryQueryOperativeListNewReq.class, req1);
        String new_xml = msgHeaderXml + xml;
        String requestXml = getSoapXml(service, new_xml);
        log.info("入参：{}", requestXml);
        List<QueryOperativeDtailNewResp> resps = new ArrayList<>();
        List<OperativeListResp> operativeListResp = new ArrayList<>();
        if (OPERATE_TYPE.equals(request.getType()) || TREATMENT_TYPE.equals(request.getType())) {
            try {
                String resultXml = getStringDataFromPhis(PHIS_PATH_URL, requestXml);
                QueryOperativeListNewResponse xml2Object = JAXBUtils.xml2Object(resultXml, QueryOperativeListNewResponse.class);
                if (CommonUtils.isNotEmpty(xml2Object) && CommonUtils.isNotEmpty(xml2Object.getMsgBody())) {
                    if ("true".equals(xml2Object.getMsgBody().getStatus())) {//返回成功
                        if (CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData()) && CommonUtils.isNotEmpty(xml2Object.getMsgBody().getData().getLists())) {
                            resps = xml2Object.getMsgBody().getData().getLists().getList();
                            //  List<QueryInspectionItemDtailResp>  list = this.transFormResqD1(resps);
                            List<OperativeListResp> list = this.transFormResqD0(resps);
                            baseResponse.setData(list);
                        }
                    } else {
                        baseResponse = BaseRespUtil.setResultError(xml2Object.getMsgBody().getDetail());
                    }
                }
            } catch (Exception e) {
                baseResponse = BaseRespUtil.setResultError("请求" + serviceName + "接口异常");
                return baseResponse;
            }
        } else {
            try {
                List<OperativeListVo> operativeListRespList=(List<OperativeListVo>) Client.rpcInvoke("cmc.baseWmDiseasesDAOService","queryDiagnosticListByPinYin",request);
                if (CommonUtils.isNotEmpty(operativeListRespList)) {
                    baseResponse.setData(operativeListRespList);
                }
            } catch (Exception e) {
                e.printStackTrace();
                BaseRespUtil.setResultError("请求baseWmDiseasesDAOService接口服务异常" + e.getMessage());
            }

        }
        return baseResponse;
    }

    //出参转化
    public List<OperativeListResp> transFormResqD0(List<QueryOperativeDtailNewResp> list) {
        List<OperativeListResp> resps = new ArrayList<>();
        if (CommonUtils.isNotEmpty(list)) {
            for (QueryOperativeDtailNewResp resp : list) {
                OperativeListResp operativeListResp = new OperativeListResp();
                operativeListResp.setRelateName(resp.getOperationName());
                operativeListResp.setRelateRecordId(resp.getOperationId());
                operativeListResp.setOperationCode(resp.getOperationCode());
                resps.add(operativeListResp);
            }
        }
        return resps;
    }


    @Override
    public BaseResponse<List<IndexTypeParameterResp>> getIndexTypeParameter(QueryIndexTypeReq request) {
        log.info("IndexHisService.getIndexTypeParameter 入参：{}", request);
        BaseResponse<List<IndexTypeParameterResp>> result = new BaseResponse<>();
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(Constants.EDITOR_FOLLOW_UP
                + Constants.CODE_LIST, jsonParams);
        log.info("IndexHisService.getIndexTypeParameter 第三方返回数据:{}", jsonObject);
        try {
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null) {
                List<IndexTypeParameterResp> list = JSONObject.parseArray(
                        jsonObject.get("data").toString(), IndexTypeParameterResp.class);
                result.setData(list);
            } else {
                result.setCode(jsonObject.getInteger("code"));
                result.setMessage(jsonObject.getString("message"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(Constants.JSON_ANALYSIS_ERR + e.getMessage());
            result.setCode(ResultCode.ERROR);
        }
        log.info("IndexHisService.getIndexTypeParameter 出参：{}", result);
        return result;
    }
}
